package com.example.night.service.ApiService;

import com.example.night.data.EsSummary.EsSummaryData;
import com.example.night.data.EsSummary.EsSummaryPackage;
import com.example.night.data.EsSummary.EsSummaryRequest;
import com.example.night.data.EsSummary.EsSummaryResponse;
import com.example.night.service.ApiService.Token.TokenService;
import com.example.night.service.ApiService.Token.TokenUpdatedEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class EsSummaryService {

    private final String BASE_URL = "https://api.jiutool.com/institutionHomeTwo/order/es_summary";
    private final TokenService tokenService;
    private static final Logger logger = LoggerFactory.getLogger(TokenService.class);

    private String token;

    public EsSummaryService(TokenService tokenService) {
        this.tokenService = tokenService;
        token = tokenService.getToken();
    }
    @EventListener
    public void handleTokenUpdated(TokenUpdatedEvent event) {
        token = event.getNewToken();
    }

    public String getFlowpoint(int flag) {
        String flow_point = "";
        switch (flag) {
            case 0:
                flow_point = "PAY_SUCC"; //支付完成
                break;
            case 1:
                flow_point = "REFUND";  //退款
                break;
            case 2:
                flow_point = "SETTLE";  //结算
                break;
            case 3:
                flow_point = "CONFIRM"; //确认收货
                break;
            default:
                flow_point = "";
                break;
        }
        return flow_point;
    }
    public String getUrl(EsSummaryRequest request, String title, int flow_point, int extend_type, String promoterId) {

        String url = UriComponentsBuilder.fromHttpUrl(BASE_URL)
                .queryParam("time_field", request.getTimeField())
                .queryParam("start_time", request.getStartTime())
                .queryParam("end_time", request.getEndTime())
                .queryParam("title", title)
                .queryParam("flow_point", flow_point == 4 ? "" : getFlowpoint(flow_point))
                .queryParam("order_id", request.getOrderId())
                .queryParam("author_account", promoterId)
                .queryParam("drsw_account_id", request.getDrswAccountId())
                .queryParam("zsyy_account_id", request.getZsyyAccountId())
                .queryParam("extend_type", extend_type == 3 ? "" : extend_type)
                .queryParam("is_drsw", request.getIsDrsw())
                .queryParam("is_zsyy", request.getIsZsyy())
                .queryParam("except_status", request.getExceptStatus())
                .queryParam("type", request.getType())
                .toUriString();

        return url;
    }
    public EsSummaryData getResponseData(ResponseEntity<String> response) {
        // 解析 JSON 响应体
        String responseBody = response.getBody();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 将响应体的 JSON 字符串转换为 EsSummaryResponse 对象
            EsSummaryResponse esSummaryResponse = objectMapper.readValue(responseBody, EsSummaryResponse.class);

            return esSummaryResponse.getData();
        } catch (Exception e) {
            e.printStackTrace();
            return null;  // 解析失败时返回 null
        }
    }
    // 请求数据的方法
    public EsSummaryPackage getEsSummaryData(String startTime, String endTime, String title, int flow_point, int extend_type, String promoterId) {
        EsSummaryPackage esSummaryPackage = new EsSummaryPackage();

        token = tokenService.getToken();
        if (token == null) {
            logger.error("获取订单数据失败：Token 为空，用户未登录");
            return null;
        }

        // 创建请求体数据
        EsSummaryRequest request = new EsSummaryRequest("pay_success_time", startTime, endTime);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + token);  // 设置 Authorization 请求头
        headers.set("X-Csrf-Token", token);     // 设置 CSRF Token
        headers.set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        // 构建请求 URL


        // 创建 HTTP 请求实体
        HttpEntity<String> entity = new HttpEntity<>(headers);

        // 使用 RestTemplate 发起请求
        RestTemplate restTemplate = new RestTemplate();
        EsSummaryData esSummaryData = new EsSummaryData();
        if (flow_point == 4) {
            String url = getUrl(request, title, 4, extend_type, promoterId);
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
            esSummaryData = getResponseData(response);

            esSummaryPackage.setOrderCount(esSummaryData.getTotalNums());
            esSummaryPackage.setOrderSysSettleMoney(esSummaryData.getTotalAmount());

            url = getUrl(request,title, 1, 3, promoterId);
            response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
            esSummaryData = getResponseData(response);

            esSummaryPackage.setRefundOrderCount(esSummaryData.getTotalNums());
            esSummaryPackage.setRefundOrderSysSettleMoney(esSummaryData.getTotalAmount());

        } else if (flow_point != 1) {
            String url = getUrl(request, title, flow_point, extend_type, promoterId);
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
            esSummaryData = getResponseData(response);
            esSummaryPackage.setOrderCount(esSummaryData.getTotalNums());
            esSummaryPackage.setOrderSysSettleMoney(esSummaryData.getTotalAmount());
            esSummaryPackage.setRefundOrderCount(0);
            esSummaryPackage.setRefundOrderSysSettleMoney(0);
        } else {
            String url = getUrl(request, title, flow_point, extend_type, promoterId);
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
            esSummaryData = getResponseData(response);
            esSummaryPackage.setOrderCount(esSummaryData.getTotalNums());
            esSummaryPackage.setOrderSysSettleMoney(esSummaryData.getTotalAmount());
            esSummaryPackage.setRefundOrderCount(esSummaryData.getTotalNums());
            esSummaryPackage.setRefundOrderSysSettleMoney(esSummaryData.getTotalAmount());
        }
        return esSummaryPackage;
    }
}
